package com.roadmap.client.module.goal;

import java.util.Date;

import org.apache.log4j.Logger;

import com.roadmap.client.module.BaseManager;
import com.roadmap.client.module.task.TaskManager;
import com.roadmap.common.BaseConst;
import com.roadmap.common.BaseEntity;
import com.roadmap.common.RdcLogger;
import com.roadmap.common.BaseEnum.ActionType;
import com.roadmap.entities.Aspirant;
import com.roadmap.entities.LifeGoal;
import com.roadmap.entities.LifeTask;
import com.roadmap.entities.MeasurableRule;
import com.roadmap.exception.ActionNotSupportedException;
import com.roadmap.exception.EntityNotFoundException;
import com.roadmap.exception.InvalidActionException;
import com.roadmap.exception.InvalidStatusException;
import com.roadmap.exception.InvalidValueException;
import com.roadmap.exception.NullObjectException;
import com.roadmap.exception.ServerException;

public class MeasurableRuleManager extends BaseManager {

	private final static Logger logger = RdcLogger.getLogger(MeasurableRuleManager.class);
	
	public MeasurableRuleManager(String aspirantId, LifeGoal parent) {
		super(aspirantId, MeasurableRule.class, parent);
		// TODO Auto-generated constructor stub
	}

	/**
	 * Check the status of MeasurableRule, only "unsatisfied" can be complete
	 */
	@Override
	public void complete(BaseEntity entity) throws NullObjectException,
			InvalidActionException, InvalidValueException, ServerException,
			EntityNotFoundException, ActionNotSupportedException {
		if (checkEntityIsValid(entity) == false) {
			return;
		}
		MeasurableRule rule = (MeasurableRule) entity;
		if(rule.getStatus()== BaseConst.RULE_STATUS_SATISFIED) {
			ActionNotSupportedException ane = new ActionNotSupportedException();
			logger.error("Only a UNSATISFIED rule supports this action.", ane);
			throw ane;
		}
		changeRuleStatus(entity, BaseConst.RULE_STATUS_SATISFIED);	
	}

	/**
	 * update the status of a MeasurableRule and its update time.
	 */
	private void changeRuleStatus(BaseEntity entity, int status)
		throws NullObjectException, InvalidActionException,
		InvalidValueException, ServerException, EntityNotFoundException {
		MeasurableRule rule = (MeasurableRule) entity;
		rule.setStatus(status);
		rule.setUpdatedTime(new Date());
		getDbUtil().update(rule);
	}
}
